/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.image.service.testImg
   Module Description   :

   Date Created      : 2010/11/2
   Original Author   : feeling.wang
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.image.service;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageProducer;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;

/**
 * @author feeling.wang
 * 
 */
public class testImg {
	static float compressRatio = 0.9f;
	static int RESIZE_WIDTH = 225;
	static int RESIZE_HEIGHT = 225;

	// 1、圖片的裝載。我們要處理圖片首先要裝載圖片到Java內存空間的圖片對象，Java用很多類來支持圖片的裝載，比如
	// a、根據圖片文件字節數組裝載圖片:
	// public Image loadImage(byte[] data) {
	// Image t = Toolkit.getDefaultToolkit().createImage(data);
	// trackImage(t, "裝載字節數組圖片");
	// return t;
	// }

	// b、根據URL來裝載圖片:
	// public Image loadImage(String urlpath) {
	// Image t = null;
	// if (a instanceof Applet) {
	// try {
	// URL u = getResourceURL(urlpath);
	// t = getApplet().getImage(u);
	// trackImage(t, urlpath);// 檢測圖片裝載過程
	// } catch (Exception e) {
	// notifyListener(MediaLoadEvent.MEDIA_LOAD_FAILED, false, e.getMessage());// 裝載失敗
	// }
	// } else {
	// t = Toolkit.getDefaultToolkit().getImage(urlpath);
	// trackImage(t, urlpath);// 檢測圖片裝載過程
	// }
	// return t;
	// }

	// public Image loadImage(String urlpath, boolean isurl) {
	// Image t = null;
	// if (isurl) {
	// try {
	// URL u = getResourceURL(urlpath);
	// t = Toolkit.getDefaultToolkit().getImage(u);
	// trackImage(t, urlpath);
	// } catch (Exception e) {
	// notifyListener(MediaLoadEvent.MEDIA_LOAD_FAILED, false, e.getMessage());// 裝載失敗
	// }
	// } else {
	// t = Toolkit.getDefaultToolkit().getImage(urlpath);
	// trackImage(t, urlpath);// 檢測圖片裝載過程
	// }
	// return t;
	// }

	// 2、圖片裝載完成後，我們可以對圖片進行處理，改變色度、亮度、對比度，翻轉、鏡像等等處理操作。在這裡我只詳細講一下最底層的像素變換調整技術，其他很多方法大都是根據這個來封裝的。
	// a、根據制定顏色值和一定範圍色差講圖片做透明處理：
	// public Image transpanent(Image repImage, Color oldColor, int errorRange) {
	// int w = repImage.getWidth(a);
	// int h = repImage.getHeight(a);
	// int[] imgdata = parImage(repImage, w, h);
	// int rr, gg, bb;
	// rr = oldColor.getRed();
	// gg = oldColor.getGreen();
	// bb = oldColor.getBlue();
	// int offr, offg, offb;
	// for (int i = 0; i < h; i++) {// 逐行掃瞄
	// for (int j = 0; j < w; j++) {// 逐列掃瞄
	// int which = i * w + j;
	// int r = ((imgdata[which] & 0xff0000 >>> 16));
	// int g = ((imgdata[which] & 0xff00 >>> 8));
	// int b = (imgdata[which] & 0xff);
	// offr = Math.abs(r - rr);
	// offg = Math.abs(g - gg);
	// offb = Math.abs(b - bb);
	// if (offr + offg + offb < errorRange) {
	// imgdata[i * w + j] = 16777215;
	// }
	// }
	// }
	// Image t = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(w, h, imgdata, 0, w));
	// trackImage(t, "裝載透明處理圖片");
	// return t;
	// }

	static void resizePressAveraging(File file) throws IOException {

		BufferedImage bufferedImage = ImageIO.read(file);
		customChange(bufferedImage, "d:/imgtest/PImg/0003/00030002/00030002_resize.jpg");
	}

	public static void customChange(BufferedImage img, String fileWholePath) {
		BufferedImage bi = img;
		try {
			double ratio = 0.0; // 縮放比例
			Image itemp = img;
			// 計算比例
			double diffH = Integer.valueOf(RESIZE_HEIGHT).doubleValue() / Integer.valueOf(bi.getHeight()).doubleValue();
			double diffW = Integer.valueOf(RESIZE_WIDTH).doubleValue() / Integer.valueOf(bi.getWidth()).doubleValue();

			if (diffH < 1 || diffW < 1) {// 只針對比設定尺寸大的做縮圖動作
				if (diffH <= diffW) {
					ratio = Integer.valueOf(RESIZE_HEIGHT).doubleValue() / bi.getHeight();
					itemp = bi.getScaledInstance(new Double(img.getWidth() * ratio).intValue(), new Double(img.getHeight()
							* ratio).intValue(), bi.SCALE_AREA_AVERAGING);
				} else if (diffH > diffW) {
					ratio = Integer.valueOf(RESIZE_WIDTH).doubleValue() / bi.getWidth();

					itemp = bi.getScaledInstance(new Double(img.getWidth() * ratio).intValue(), new Double(img.getHeight()
							* ratio).intValue(), bi.SCALE_AREA_AVERAGING);
				}
			}
			BufferedImage image = new BufferedImage(RESIZE_WIDTH, RESIZE_HEIGHT, BufferedImage.TYPE_INT_RGB);
			Graphics2D g = image.createGraphics();
			g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
			g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
			g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
			g.setColor(Color.white);
			g.fillRect(0, 0, RESIZE_WIDTH, RESIZE_HEIGHT);
			if (RESIZE_WIDTH == itemp.getWidth(null)) {
				g.drawImage(itemp, 0, (RESIZE_HEIGHT - itemp.getHeight(null)) / 2, itemp.getWidth(null), itemp.getHeight(null),
						Color.white, null);
			} else if (RESIZE_HEIGHT == itemp.getHeight(null)) {
				g.drawImage(itemp, (RESIZE_WIDTH - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null),
						Color.white, null);
			} else {
				g.drawImage(itemp, (RESIZE_WIDTH - itemp.getWidth(null)) / 2, (RESIZE_HEIGHT - itemp.getHeight(null)) / 2,
						itemp.getWidth(null), itemp.getHeight(null), Color.white, null);
			}
			g.dispose();
			itemp = image;
			Iterator<ImageWriter> it = ImageIO.getImageWritersBySuffix("jpg");
			if (it.hasNext()) {
				FileImageOutputStream fileImageOutputStream = new FileImageOutputStream(new File(fileWholePath));

				ImageWriter iw = it.next();
				ImageWriteParam iwp = iw.getDefaultWriteParam();
				iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
				iwp.setCompressionQuality(compressRatio);
				iw.setOutput(fileImageOutputStream);
				iw.write(null, new IIOImage((BufferedImage) itemp, null, null), iwp);
				iw.dispose();
				fileImageOutputStream.flush();
				fileImageOutputStream.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// b、對圖片做剪切處理，這裡使用了圖片處理過濾類CropImageFilter，類似的過濾器很多，分別實現不同要求的圖片處理變換。
	public static Image crop(int x, int y, int w, int h, Image img) throws IOException {
		ImageFilter filter = new CropImageFilter(x, y, w, h);
		ImageProducer producer = new FilteredImageSource(img.getSource(), filter);
		Image t = Toolkit.getDefaultToolkit().createImage(producer);
		BufferedImage im = new BufferedImage(378, 500, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = im.createGraphics();
		g.drawImage(t, 0, 0, 378, 500, null);
		g.dispose();
		ImageIO.write(im, "jpg", new File("d:/imgtest/PImg/0003/00030002/00030002_cut.jpg"));

		// trackImage(t, "裝載剪切圖片");
		return t;
	}

	public static void main(String[] args) throws IOException {
		File file = new File("d:/imgtest/PImg/0003/00030002/00030002_m500.jpg");
		Image img = ImageIO.read(file);
		System.out.println("1----------");
		crop(61, 0, 378, 500, img);
		System.out.println("2----------");
		File file2 = new File("d:/imgtest/PImg/0003/00030002/00030002_cut.jpg");
		resizePressAveraging(file2);
	}

	// 3、圖片復合和繪製圖片：
	// 使用Java的繪圖類，可對多個圖片進行疊加，並可以自定義繪製各種圖形圖像，比如實現圖片水印、驗證碼圖片，疊加banner圖片等。

	// public static void createImagePNG(String signcode, OutputStream out) {
	// BufferedImage offimg = null;
	// Graphics offgra = null;
	// while (offimg == null || offgra == null) {
	// if (offimg == null) {
	// offimg = new BufferedImage(50, 18, BufferedImage.TYPE_INT_RGB);
	// }
	// if (offgra == null && offimg != null) {
	// offgra = offimg.getGraphics();
	// }
	// }
	// offgra.setColor(new Color(235, 235, 235));
	// offgra.fillRect(0, 0, 50, 18);
	// /*
	// * for(int i=0;i<12;i++){//生成混淆背景，也可用混淆背景圖片
	// * offgra.setColor(Color.decode("#"+color[SystemTool.getRandom(0,color.length-1)]));
	// * offgra.fillOval(SystemTool.getRandom(0,48),SystemTool.getRandom(0,18),1,1);//10,4); }
	// */
	// offgra.setColor(Color.red);
	// // offgra.setColor(Color.decode("#"+color[SystemTool.getRandom(0,color.length-1)]));
	// try {
	// Font font = Font.createFont(Font.TRUETYPE_FONT, com.sunstudio.util.ClassLoaderEx
	// .getResourceInputStream(SystemConfig.getParameter("validate_font")));// FileInputStream("c:\\\\comicbd.ttf"));
	// offgra.setFont(font.deriveFont(Font.BOLD, 18F));
	// } catch (Exception e) {
	// }
	// offgra.drawString(signcode, 1, 14);
	// PngEncoder png = new PngEncoder(Toolkit.getDefaultToolkit().createImage(offimg.getSource()),
	// PngEncoder.ENCODE_ALPHA, PngEncoder.FILTER_LAST, 3);
	// try {
	// out.write(png.pngEncode());
	// } catch (Exception e) {
	// }
	// offgra.dispose();
	// }

}
